import { defineStore} from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user/index'
import type { loginForm, responseData, userInfo } from '@/api/user/type'
import type { UserState } from './types/types'
import { reactive } from 'vue'
import { SET_TOKEN, GET_TOKEN, GET_USERNAME, GET_AVATAR, REMOVE_TOKEN } from '@/utils/token'
import { constantRoute } from '@/router/routes'

let UseUserStore = defineStore('User', () =>{
  let user: UserState = reactive({
    token: GET_TOKEN(),
    menu: constantRoute,
    userName: GET_USERNAME(),
    avatar: GET_AVATAR()
  })

  const userLogin = async (data: loginForm) => {
    let res:responseData<string> = await reqLogin(data)
    if(res.code === 200) {
      user.token = res.data as string
      SET_TOKEN(res.data as string)
      return 'ok'
    } else {
      return Promise.reject(new Error(res.data))
    }
  }
  const userInfo = async () => {
    let res:responseData<userInfo> = await reqUserInfo()
    if (res.code === 200) {
      user.userName = res.data.name
      user.avatar = res.data.avatar
      return 'ok'
    } else {
      return Promise.reject(new Error('获取用户信息失败'))
    }
  }
  const userLogOut = async () => {
    let res: responseData<any> = await reqLogout()
    if (res.code === 200) {
      user.token = ''
      user.avatar = ''
      user.userName = ''
      REMOVE_TOKEN()
      return 'ok'
    } else {
      return Promise.reject(new Error('退出登录失败'))
    }
  }
  return {
    user,
    userLogin,
    userInfo,
    userLogOut
  }
})

export default UseUserStore
